<template>
  <PageWrapper title="订单管理" contentFullHeight>
    <BasicTable @register="register" :dataSource="state.orderList" :pagination="state.pagination">
      <template #pay_status="{ record }">
        <a-tag v-if="record.pay_status == 0" color="red">未付款</a-tag>
        <a-tag v-if="record.pay_status == 1" color="green">已付款</a-tag>
      </template>
      <template #create_time="{ record }">
        <span>{{ moment(record.add_time).format('YYYY-MM-DD HH:mm:ss') }}</span>
      </template>
      <template #operations="{ record }">
        <TableAction
          stopButtonPropagation
          :actions="[
            {
              label: '编辑',
              icon: 'ant-design:edit-outlined',
              onClick: handleEdit.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
          ]"
        />
      </template>
    </BasicTable>
  </PageWrapper>
  <editModal
    :editStatus="state.editStatus"
    :editRow="state.editRow"
    @register="modalRegister"
    @edit-result="editResult"
  />
</template>

<script lang="ts" setup>
  import { onMounted, reactive } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useShopOrdersStore } from '/@/store/modules/shopOrdersStore';
  import moment from 'moment';
  import editModal from './editModal.vue';
  import { useModal } from '/@/components/Modal';
  import { depthFirstSearch } from '/@/utils/common';
  // import { logisticsApi } from '/@/api/shopper/shopOrdersApi';

  type stateModel = {
    orderList: object[] | any;
    pagination: object | any;
    query: object | any;
    editStatus: boolean;
    editRow: object | any;
  };

  const shopOrdersStore = useShopOrdersStore();

  const [modalRegister, { openModal }] = useModal();

  const state: stateModel = reactive({
    orderList: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
    },
    query: {
      user_id: null,
      pay_status: null,
      is_send: null,
      order_fapiao_title: null,
      order_fapiao_company: null,
      order_fapiao_content: null,
      consignee_addr: null,
    },
    editStatus: false,
    editRow: {},
  });

  const getOrderData = async (params: object | any) => {
    try {
      const data = await shopOrdersStore.getOrderList(params);
      const { goods, total } = data;
      state.orderList = goods;
      state.pagination.total = total;
    } catch (error) {
      console.log(error);
    }
  };

  const getSingleOrderData = async (id: number | string) => {
    try {
      const data = await shopOrdersStore.getSingleOrder({ id });
      state.editRow = data;
    } catch (error) {
      console.log(error);
    }
  };

  // const getLogisticsData = async (id: number | string) => {
  //   try {
  //     const data = await logisticsApi({ id });
  //     console.log(data);
  //   } catch (error) {
  //     console.log(error);
  //   }
  // };

  const handleEdit = (record: any) => {
    getSingleOrderData(record.order_id);
    // getLogisticsData(record.order_id);
    openModal();
  };

  const editResult = (data: any) => {
    depthFirstSearch(state.orderList, (item, key) => {
      if (item.order_id == data.order_id) {
        state.orderList[key] = data;
      }
    });
  };

  onMounted(() => {
    const { current, pageSize } = state.pagination;
    const { query } = state;
    getOrderData({ pagenum: current, pagesize: pageSize, ...query });
  });

  const [register, { getForm }] = useTable({
    title: '订单列表',
    titleHelpMessage: 'orders',
    rowKey: (record: any) => {
      return record.order_id;
    },
    columns: [
      {
        title: '订单编号',
        dataIndex: 'order_number',
      },
      {
        title: '订单价格',
        dataIndex: 'order_price',
      },
      {
        title: '支付状态',
        dataIndex: 'pay_status',
        slots: { customRender: 'pay_status' },
      },
      {
        title: '是否发货',
        dataIndex: 'is_send',
      },
      {
        title: '下单时间',
        dataIndex: 'create_time',
        slots: { customRender: 'create_time' },
      },
    ],
    striped: true,
    bordered: true,
    showTableSetting: false,
    useSearchForm: true,
    formConfig: {
      labelWidth: 100,
      autoAdvancedLine: 4,
      schemas: [
        {
          field: `user_id`,
          label: `用户ID`,
          component: 'Input',
          colProps: {
            xl: 12,
            xxl: 8,
          },
          // componentProps: {
          //   onChange: (e: any) => {
          //     if (!e.target.value) {
          //       state.query.user_id = null;
          //     }
          //   },
          // },
        },
        {
          field: `pay_status`,
          label: `支付状态`,
          component: 'Select',
          colProps: {
            xl: 12,
            xxl: 8,
          },
          componentProps: {
            options: [
              {
                label: '未付款',
                value: '0',
                key: '0',
              },
              {
                label: '已付款',
                value: '1',
                key: '1',
              },
            ],
          },
        },
        {
          field: `is_send`,
          label: `是否发货`,
          component: 'Select',
          colProps: {
            xl: 12,
            xxl: 8,
          },
          componentProps: {
            options: [
              {
                label: '未发货',
                value: '0',
                key: '0',
              },
              {
                label: '已发货',
                value: '1',
                key: '1',
              },
            ],
          },
        },
        {
          field: `order_fapiao_title`,
          label: `发票抬头`,
          component: 'Select',
          colProps: {
            xl: 12,
            xxl: 8,
          },
          componentProps: {
            options: [
              {
                label: '个人',
                value: '个人',
                key: '0',
              },
              {
                label: '公司',
                value: '公司',
                key: '1',
              },
            ],
          },
        },
        {
          field: `order_fapiao_company`,
          label: `公司名称`,
          component: 'Input',
          colProps: {
            xl: 12,
            xxl: 8,
          },
        },
        {
          field: `order_fapiao_content`,
          label: `发票内容`,
          component: 'Input',
          colProps: {
            xl: 12,
            xxl: 8,
          },
        },
        {
          field: `consignee_addr`,
          label: `发货地址`,
          component: 'Input',
          colProps: {
            xl: 12,
            xxl: 8,
          },
        },
      ],
      submitFunc: () => {
        if (getForm().getFieldsValue()) {
          state.query = getForm().getFieldsValue();
          const { current, pageSize } = state.pagination;
          const { query } = state;
          state.pagination.current = current;
          state.pagination.pageSize = pageSize;
          getOrderData({ pagenum: current, pagesize: pageSize, ...query });
        }
        return Promise.resolve();
      },
      resetFunc: () => {
        for (const key in state.query) {
          state.query[key] = null;
        }
        return Promise.resolve();
      },
    },
    actionColumn: {
      title: '操作',
      dataIndex: 'operations',
      slots: { customRender: 'operations' },
      width: 200,
    },
    onChange: (pagination) => {
      const { current, pageSize } = pagination;
      const { query } = state;
      state.pagination.current = current;
      state.pagination.pageSize = pageSize;
      getOrderData({ pagenum: current, pagesize: pageSize, ...query });
    },
  });
</script>
